<template>
  <div>
    <!-- 整体布局 -->
    <el-row>
      <el-col :span="4"><left-menu @pushTypeValue='getTypeValue' /></el-col>
      <el-col :span="20">
        <div class="shadowBox"></div>
        <div class="operationBanner">
          <h2>当前操作科属：{{ typeValue }}</h2>
          <div class="searchDiv">
            <el-icon><FolderAdd /></el-icon>
            <p style="margin: 0 15px 0 5px;" @click="addData">添加花卉</p>
            <el-input
              style="width: 300px"
              v-model="inputData"
              placeholder="搜索花卉"
              clearable
              @change="changeInput"
            >
              <template #append>
                <el-icon @click="searchData"><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
        <div class="showData">
          <div v-if="dataList.length == 0">
            <h2>未查找到数据！</h2>
          </div>
          <template v-for="(v, k) in dataList" :key="k">
            <div class="showDataItem">
              <el-image class="itemImg" :src="showCover(v.imgPath)" fit="cover" />
              <div class="itemText">
                <div :title="v.lauraceae">科属：{{ v.lauraceae }}</div>
                <div :title="v.name">名称：{{ v.name }}</div>
                <div :title="v.price">价格：{{ v.price }}</div>
              </div>
              <el-button type="primary" class="itemButton" @click="openDrawer(k)">
                修改商品
              </el-button>
            </div>
          </template>
          <template v-for="v in itemAllList(dataList)">  
            <div class="emptyDataItem"></div>
          </template>
        </div>
      </el-col>
    </el-row>

    <!-- 修改弹出框 -->
    <el-drawer
      v-model="drawer"
      title="数据修改页面"
      :before-close="changeHandleClose"
      size="80%"
    >
      <el-form
        label-position="top"
        label-width="400px"
        v-model="dataList[theId]"
        class="formStyle"
        >
        <!-- 轮播图 -->
        <el-form-item label="轮播图" class="rotationImg">
          <div v-for="(v, k) in getRotasionImg(dataList[theId].imgPath)" :key="k">
            <el-image style="width: 100px; height: 100px; margin: 0 5px" :src="v" alt="" fit="cover" />
          </div>
        </el-form-item>
        <!-- 商品介绍图 -->
        <el-form-item label="介绍图" class="flowerDetailImg">
          <div v-for="(v, k) in getFlowerDetailImg(dataList[theId].imgPath)" :key="k">
            <el-image style="width: 100px; height: 100px; margin: 0 5px" :src="v" alt="" fit="cover" />
          </div>
        </el-form-item>

        <el-form-item label="名称">
          <el-input v-model="dataList[theId].name" />
        </el-form-item>

        <el-form-item label="科属">
          <el-input v-model="dataList[theId].lauraceae" />
        </el-form-item>
        
        <el-form-item label="价格">
          <el-input v-model="dataList[theId].price" />
        </el-form-item>

        <el-form-item label="描述">
          <el-input v-model="dataList[theId].details" />
        </el-form-item>
        
        <el-form-item label="相关描述">
          <div style="border: 1px solid #ccc; margin-top: 10px">
            <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
              style="border-bottom: 1px solid #ccc"
            />
            <Editor
              :defaultConfig="editorConfig"
              :mode="dataList[theId].richtext"
              v-model="dataList[theId].richtext"
              style="height: 350px; overflow-y: hidden"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitChangeData(dataList[theId])">提交修改</el-button>
          <el-button @click="cancelData(theId)">取消修改</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="deleteData(dataList[theId])">删除产品</el-button>
        </el-form-item>
        
      </el-form>
    </el-drawer>

    <!-- 增加弹出框 -->
    <el-drawer
      v-model="addDrawer"
      title="数据添加页面"
      :before-close="addHandleClose"
      size="80%"
    >
      <el-form
        label-position="top"
        label-width="400px"
        v-model="dataList"
        class="formStyle"
        >
        <!-- 轮播图 -->
        <el-form-item label="轮播图" class="rotationImg">
          <el-upload
            action=""
            multiple
            v-model:file-list="rotationList"
            :auto-upload="false"
            list-type="picture-card"
            :on-remove="rotationHandleRemove"
            :on-change="rotationUploadFile"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <!-- 商品介绍图 -->
        <el-form-item label="介绍图" class="flowerDetailImg">
          <el-upload
            action=""
            multiple
            v-model:file-list="detailList"
            :auto-upload="false"
            list-type="picture-card"
            :on-remove="detailHandleRemove"
            :on-change="detailUploadFile"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="类型">
          <el-select v-model="addDataList.type" class="m-2" placeholder="请选择" size="large">
            <el-option
            v-for="item in typeLabel"
            :key="item.type"
            :label="item.label"
            :value="item.type"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="名称">
          <el-input v-model="addDataList.name" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="科属">
          <el-input v-model="addDataList.lauraceae" placeholder="请输入内容"/>
        </el-form-item>
        
        <el-form-item label="价格">
          <el-input v-model="addDataList.price" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="描述">
          <el-input v-model="addDataList.details" placeholder="请输入内容"/>
        </el-form-item>
        
        <el-form-item label="相关描述">
          <div style="border: 1px solid #ccc; margin-top: 10px">
            <Toolbar
              :editor="addEditorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
              style="border-bottom: 1px solid #ccc"
            />
            <Editor
              :defaultConfig="editorConfig"
              :mode="addDataList.richtext"
              v-model="addDataList.richtext"
              style="height: 350px; overflow-y: hidden"
              @onCreated="addHandleCreated"
            />
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitAddData(addDataList)">提交修改</el-button>
        </el-form-item>
        
      </el-form>
    </el-drawer>
    
    <div class="limitBox">
      <el-pagination
        @current-change="handleCurrentChange"
        background 
        :current-page="nowLimit"
        :pager-count="5" 
        layout="prev, pager, next" 
        :total="total"
      />
    </div>
    
  </div>
</template>

<script>
  import {ref, computed, onBeforeUnmount, shallowRef} from 'vue';
  import {ElMessageBox, ElMessage, ElLoading} from 'element-plus';
  import {request} from '../network/request';
  import LeftMenu from '@/components/LeftMenu.vue';
  import '@wangeditor/editor/dist/css/style.css';
  import {Editor, Toolbar} from '@wangeditor/editor-for-vue';

  export default {
    components: {
      "left-menu": LeftMenu,
      "Editor": Editor,
      "Toolbar": Toolbar 
    },
    setup() {
      const typeLabel = ref([
        {'label': '花卉', 'type': 0},
        {'label': '树苗', 'type': 1},
      ]);
      const inputData = ref('');
      const typeValue = ref('');
      const typeNum = ref(0);
      const offset = ref(0);
      const dataList = ref([]);
      const rotationList = ref([]);
      const detailList = ref([]);
      const addDataList = ref({
        type: 0,
        name: '',
        lauraceae: '',
        price: 0,
        imgPath: '',
        richtext: '',
        details: '',
      });
      const emptyData = ref({});
      const rotationImg = ref([]);
      const detailImg = ref([]);
      const fileStore = ref('');
      const total = ref(0);
      const theId = ref(0);
      const drawer = ref(false);
      const addDrawer = ref(false);
      const originData = ref({});
      const nowLimit = ref(1);

      // 获取分类项
      const getTypeValue = value => {
        const {type, lauraceae} = value;
        typeNum.value = type;
        typeValue.value = lauraceae;
        getAllProductData();
      }

      // 请求商品数据
      const getAllProductData = () => {
        request({
          // url: '/api/flower/flowerListByLauraceae',
          url: '/flower/flowerListByLauraceae',
          params: {
            type: typeNum.value,
            lauraceae: typeValue.value,
            offset: offset.value,
            size: 10
          }
        }).then(res => {
          dataList.value = res.result;
          total.value = res.total;
        }).catch(err => {
          console.log(err);
        })
      }
      
      // 输入框更改
      const changeInput = value => {
        inputData.value = value;
      }

      // 提交输入框
      const searchData = () => {
        if (inputData.value != '') {
          request({
            // url: '/api/flower/flowerListByName',
            url: '/flower/flowerListByName',
            params: {
              type: typeNum.value,
              flowerName: inputData.value,
              offset: offset.value,
              size: 10
            }
          }).then(res => {
            inputData.value = '';
            if (total != 0) {
              dataList.value = res.result;
              total.value = res.total;
            }
          }).catch(err => {
            console.log(err);
          })
        }
      }
      
      // 打开修改抽屉
      const openDrawer = id => {
        theId.value = id;
        drawer.value = true;
        
        for (let k in dataList.value[id]) {
          originData.value[k] = dataList.value[id][k];
        }
      }

      // 关闭修改抽屉
      const changeHandleClose = done => {
        ElMessageBox.confirm('是否退出编辑？')
          .then(() => {
            done();
          })
          .catch(() => {
            console.log('取消');
          })
      }

      // 提交修改数据
      const submitChangeData = item => { 
        const data = ref({});
        for (let k in item) {
          if (k != 'imgName' && k != 'imgPath') {
            data.value[k] = item[k];
          }
        }
        request({
          // url: '/api/upload/uploadInfo',
          url: '/upload/uploadInfo',
          headers: {'Content-Type': 'multipart/form-data'},
          method: 'post',
          data: data.value
        }).then(res => {
          // console.log(res);
          ElMessageBox.alert('数据已保存，等待刷新', '提示', {
            type: 'success'
          });
          setTimeout(() => {
            drawer.value = false;
            location.reload();
          }, 500);
        }).catch(err => {
          console.log(err);
        })
      }

      // 取消编辑
      const cancelData = id => {
        ElMessageBox.confirm('是否取消编辑？')
          .then(() => {
            for (let k in originData.value) {
              dataList.value[id][k] = originData.value[k];
            }
          })
          .catch(() => {
            console.log('取消');
          })
      }

      // 删除商品
      const deleteData = item => {
        const {type, id} = item;
        ElMessageBox.confirm('是否删除此条数据？')
          .then(() => {
            request({
              // url: '/api/flower/deleteData',
              url: '/flower/deleteData',
              method: 'delete',
              params: {
                id,
                type
              }
            }).then(res => {
              if (res == 'Success') {
                ElMessage({
                  type: 'success',
                  message: '删除当前商品成功！',
                })
                location.reload();
              }
            }).catch(err => {
              console.log(err);
            })

          })
          .catch(() => {})
      }
      
      // 增加数据抽屉判断
      const addData = () => {
        addDrawer.value = true;
        for (let k in addDataList.value) {
          emptyData.value[k] = addDataList.value[k];
        }
      }

      // 关闭修改抽屉
      const addHandleClose = done => {
        ElMessageBox.confirm('是否退出编辑？')
        .then(() => {
          // 取消编辑时清空上传图片
          rotationImg.value = [];
          rotationList.value = [];
          detailImg.value = [];
          detailList.value = [];
          // 取消编辑时恢复默认值
          for (let k in emptyData.value) {
            addDataList.value[k] = emptyData.value[k];
          }
          done();
          })
          .catch(() => {
            console.log('取消');
          })
      }
      
      // 增加数据
      const submitAddData = data => {
        const {type, name, lauraceae, price, richtext, details} = data;
        // 判断是否为空，否则禁止提交
        if (name != '' && lauraceae != '' && richtext != '' && details != '' && rotationImg.value.length != 0 && detailImg.value.length != 0) {
          const loading = ElLoading.service({
            lock: true,
            text: '正在上传数据，请等候。。。',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          
          request({
            // url: '/api/upload/uploadInfo',
            url: '/upload/uploadInfo',
            headers: {'Content-Type': 'multipart/form-data'},
            method: 'post',
            data: {
              type,
              name,
              lauraceae,
              price,
              rotationImg: rotationImg.value,
              flowerDetailImg: detailImg.value,
              richtext,
              details
            }
          }).then(res => {
            loading.close();
            ElMessageBox.alert(`${res}，等待刷新`, '提示', {
              type: 'success'
            });
            setTimeout(() => {
              addDrawer.value = false;
              location. reload();
            }, 500);
          }).catch(err => {
            console.log(err);
          })
        } else {
          ElMessage({
            type: 'error',
            message: '禁止提交，请检查数据是否全部填写！'
          })
        }
      }

      // 删除轮播预览文件
      const rotationHandleRemove = (file, fileList) => {
        rotationImg.value = [];
        for (let k in fileList) {
          rotationImg.value.push(fileList[k].raw);
        }
      }

      // 轮播图片文件上传
      const rotationUploadFile = file => {
        //参数file文件就是传入的文件流，添加进formData中
        rotationImg.value.push(file.raw);
      }

      // 删除详情预览文件
      const detailHandleRemove = (file, fileList) => {
        detailImg.value = [];
        for (let k in fileList) {
          detailImg.value.push(fileList[k].raw);
        }
      }

      // 详情图片文件上传
      const detailUploadFile = file => {
        //参数file文件就是传入的文件流，添加进formData中
        detailImg.value.push(file.raw);
      }
      
      // 分页查询数值
      const handleCurrentChange = data => {
        nowLimit.value = data;
        if (data == 1) {
          offset.value = 0;
        } else {
          offset.value += (data - 1) * 10;
        }
        getAllProductData();
      }

      // 计算属性
      // 补充盒子
      const itemAllList = computed(() => {
        return dataList => {
          return 5 - dataList.length % 5;
        }
      })
      
      // 封面展示
      const showCover = computed(() => {
        return imgs => {
          return JSON.parse(imgs)[0].filename;
        }
      })

      // 轮播图
      const getRotasionImg = computed(() => {
        return imgs => {
          let originImgsArray = ref([]);
          let originImgs = JSON.parse(imgs);
          for (let i in originImgs) {
            if (originImgs[i].fieldname == 'rotationImg') {
              originImgsArray.value.push(originImgs[i].filename);
            }
          }
          return originImgsArray.value;
        }

      })

      // 商品介绍图
      const getFlowerDetailImg = computed(() => {
        return imgs => {
          let originImgsArray = ref([]);
          let originImgs = JSON.parse(imgs);
          for (let i in originImgs) {
            if (originImgs[i].fieldname == 'flowerDetailImg') {
              originImgsArray.value.push(originImgs[i].filename);
            }
          }
          return originImgsArray.value;
        }
      })

      // 编辑器实例，必须用 shallowRef，重要！
      const editorRef = shallowRef();
      const addEditorRef = shallowRef();
      const toolbarConfig = {};
      const editorConfig = { placeholder: '请输入内容...' };
      // 组件销毁时，也及时销毁编辑器，重要！
      onBeforeUnmount(() => {
        const editor = editorRef.value;
        if (editor == null) return;

        editor.destroy();
      });

      // 编辑器回调函数
      const handleCreated = (editor) => {
        // console.log('created', editor);
        editorRef.value = editor; // 记录 editor 实例，重要！
      };
      const addHandleCreated = (editor) => {
        addEditorRef.value = editor;
      };
      const customPaste = (editor, event, callback) => {
        console.log('ClipboardEvent 粘贴事件对象', event);

        // 返回值（注意，vue 事件的返回值，不能用 return）
        callback(false); // 返回 false ，阻止默认粘贴行为
        // callback(true) // 返回 true ，继续默认的粘贴行为
      };

      return {
        typeLabel,
        inputData,
        typeValue,
        typeNum,
        offset,
        dataList,
        rotationList,
        detailList,
        addDataList,
        emptyData,
        rotationImg,
        detailImg,
        fileStore,
        total,
        theId,
        drawer,
        addDrawer,
        originData,
        nowLimit,
        getTypeValue,
        getAllProductData,
        changeInput,
        searchData,
        openDrawer,
        changeHandleClose,
        submitChangeData,
        cancelData,
        deleteData,
        addData,
        submitAddData,
        addHandleClose,
        rotationHandleRemove,
        rotationUploadFile,
        handleCurrentChange,
        detailUploadFile,
        detailHandleRemove,
        itemAllList,
        showCover,
        getRotasionImg,
        getFlowerDetailImg,
        editorRef,
        addEditorRef,
        mode: 'default',
        toolbarConfig,
        editorConfig,
        handleCreated,
        addHandleCreated,
        customPaste
      };
    }
}

</script>

<style scoped>
  .shadowBox {
    width: 100%;
    height: 59px;
  }
  .operationBanner {
    width: 100%;
    height: 48px;
    line-height: 48px;
    margin-bottom: 10px;
    box-shadow: 0px 2px 3px 3px #eee;
    display: flex;
    justify-content: space-between;
  }
  .searchDiv {
    display: flex;
    align-items: center;
  }
  .showData {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
  }
  .showDataItem {
    width: 18%;
    height: 280px;
    font-size: 1.2em;
    border: 1px solid #ddd;
    border-radius: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 20px;
  }
  .emptyDataItem {
    width: 18%;
    border-radius: 10px;
    margin-bottom: 20px;
  }
  .itemImg {
    width: 100%;
    height: 150px;
    display: block;
    margin: 0 auto;
  }
  .itemText {
    width: 95%;
    line-height: 1.4em;
    margin: 5px auto 0;
  }
  .itemButton {
    display: block;
    /* margin-top: 10px; */
    margin: 5px auto 0;
  }
  /* .rightContral {
    
  } */
  .formStyle {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  .rotationImg, .flowerDetailImg {
    width: 100%;
    background-color: #f3f3f3;
  }
  .limitBox {
    width: auto;
    height: 34px;
    display: flex;
    justify-content: center;
    margin: auto;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: -700px;
    z-index: 9;
  }
</style>